<template>
  <view class="container">
    <view v-for="(item, idx) in goodsList" :key="item.id" class="goods-card">
      <view class="goods-top">
        <image class="goods-img" :src="item.picUrl" mode="aspectFill" />
        <view class="goods-info">
          <view class="goods-title">{{ item.name }}</view>
          <view class="goods-price"
            ><view>￥{{ item.price }}</view
            ><view>x{{ item.num }}</view></view
          >
        </view>
      </view>
      <view class="goods-bottom">
        <picker
          class="picker"
          :range="expressList"
          :value="item.expressIndex"
          range-key="name"
          @change="onExpressChange(idx, $event)"
        >
          <view class="picker-inner">
            <text v-if="item.expressIndex == -1">{{ "请选择快递公司" }}</text>
            <text v-else>{{ expressList[item.expressIndex].name }}</text>
          </view>
        </picker>
        <input
          type="text"
          class="numberinput"
          v-model="item.expressNo"
          placeholder="请输入物流单号"
          maxlength="50"
        />
        <!-- <view class="search" @click="toLogistics(item)">
          <image class="picker-icon" src="/static/img/search-icon2.png" />
        </view> -->
      </view>
    </view>
    <button
      class="submit-btn"
      :style="{ backgroundColor: t('color1') }"
      @tap="onSubmit"
    >
      提交
    </button>
  </view>
</template>

<script>
var app = getApp();
export default {
  data() {
    return {
      id: "",
      goodsList: [
        // {
        //   id: 1,
        //   name: "品A商品A商品A商品A商品A商品A商品A商品A商品A商品A商品A商品A商品A商品A商品A商品A商品A商品A商品A商品A商品A商品A商品A商",
        //   price: "99.00",
        //   num: 1,
        //   picUrl:
        //     "https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250121/e41d7fe8ead48f06290c699d6d6d36e9.jpg",
        //   expressIndex: -1,
        //   expressNo: "",
        // },
        // {
        //   id: 2,
        //   name: "商品B",
        //   price: "188.00",
        //   num: 5,
        //   picUrl:
        //     "https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250121/e41d7fe8ead48f06290c699d6d6d36e9.jpg",
        //   expressIndex: -1,
        //   expressNo: "",
        // },
      ],
      expressList: [
        // "顺丰快递", "圆通快递", "中通快递", "申通快递", "韵达快递"
      ],
      detail: {},
    };
  },
  onLoad(opt) {
    this.id = opt.id;
    console.log("订单ID:", this.id);
    this.getRefundData();
    this.getexpressCom();
    this.getLogistics();
  },
  methods: {
    getRefundData() {
      var that = this;
      app.showLoading("加载中");
      app.get("Order/refundDetail", { id: that.id }, function (res) {
        app.showLoading(false);
        that.detail = res.detail;
        // that.prolist = res.prolist;
        that.goodsList = res.prolist.map((item) => ({
          id: item.ogid,
          name: item.name,
          price: item.sell_price,
          num: item.refund_num,
          picUrl: item.pic,
          expressIndex: -1,
          expressNo: "",
        }));
      });
    },

    getexpressCom() {
      let that = this;
      app.get("Order/getSendExpress", {}, function (res) {
        if (res.code == 200) {
          that.expressList = Object.keys(res.data).map((key) => {
            return {
              name: key, // 快递名称
              value: res.data[key], // 快递编码
            };
          });
          // console.log("快递公司列表:", that.expressList);
        }
      });
    },

    getLogistics() {
      var that = this;
      app.get(
        "Order/refundLogistics",
        {
          id: that.id,
        },
        function (res) {
          if (res.data.type == 1) {
            if (res.data.datalist.State == -1) {
              return;
            }
            var datalist = [
              {
                express_com: that.detail.express_com,
                express_no: that.detail.express_no + ":0",
                express_ogids: that.detail.express_ogids,
              },
            ];

            datalist.forEach((dataItem) => {
              // 在 that.goodsList 中查找匹配的 id
              const matchedGoods = that.goodsList.find(
                (goods) => goods.id == dataItem.express_ogids
              );
              if (matchedGoods) {
                // 设置 expressNo（取 : 前面的部分）
                if (dataItem.express_no) {
                  matchedGoods.expressNo = dataItem.express_no.split(":")[0];
                }
                // 设置 expressIndex（在 that.expressList 中查找索引）
                if (dataItem.express_com) {
                  const index = that.expressList.findIndex(
                    (expressItem) => expressItem.value === dataItem.express_com
                  );
                  matchedGoods.expressIndex = index !== -1 ? index : null;
                }
              }
            });
          }
          if (res.data.type == 2) {
            // 遍历 res.data.datalist 和 that.goodsList
            res.data.datalist.forEach((dataItem) => {
              // 在 that.goodsList 中查找匹配的 id
              const matchedGoods = that.goodsList.find(
                (goods) => goods.id == dataItem.express_ogids
              );
              if (matchedGoods) {
                // 设置 expressNo（取 : 前面的部分）
                if (dataItem.express_no) {
                  matchedGoods.expressNo = dataItem.express_no.split(":")[0];
                }
                // 设置 expressIndex（在 that.expressList 中查找索引）
                if (dataItem.express_com) {
                  const index = that.expressList.findIndex(
                    (expressItem) => expressItem.value === dataItem.express_com
                  );
                  matchedGoods.expressIndex = index !== -1 ? index : null;
                }
              }
            });
          }
        }
      );
    },

    onExpressChange(idx, e) {
      this.goodsList[idx].expressIndex = e.detail.value;
    },
    toLogistics(item) {
      if (item.expressIndex === -1 || !item.expressNo.trim()) {
        uni.showToast({ title: "请填写完整信息再查询", icon: "none" });
        return;
      }
      app.goto(
        "/pagesExt/order/refundLogistics?express_com=" +
          this.expressList[item.expressIndex].value +
          "&express_no=" +
          item.expressNo
      );
    },
    onSubmit() {
      const expressArr = [];
      const expressNoArr = [];
      const goodsIdArr = [];
      for (let item of this.goodsList) {
        if (item.expressIndex === -1 || !item.expressNo.trim()) {
          uni.showToast({ title: "请填写完整物流信息", icon: "none" });
          return;
        }
        expressArr.push(this.expressList[item.expressIndex].value);
        expressNoArr.push(item.expressNo.trim());
        goodsIdArr.push(item.id);
      }
      console.log("快递公司数组:", expressArr);
      console.log("快递单号数组:", expressNoArr);
      console.log("商品ID数组:", goodsIdArr);
      app.showLoading("提交中");
      // 提交逻辑
      app.post(
        "Order/refundSendExpress",
        {
          id: this.id,
          express_com: expressArr.join(","),
          express_no: expressNoArr.join(","),
          express_ogids: goodsIdArr.join(","),
        },
        function (res) {
          app.showLoading(false);
          if (res.code == 200) {
            uni.showToast({ title: "提交成功", icon: "success" });
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          } else {
            uni.showToast({ title: res.msg, icon: "none" });
          }
        }
      );
    },
  },
};
</script>

<style scoped>
.container {
  padding: 32rpx;
  padding-bottom: 120rpx;
}
.goods-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 2rpx 8rpx #f0f1f2;
  padding: 24rpx;
}
.goods-top {
  display: flex;
  align-items: center;
  margin-bottom: 18rpx;
}
.goods-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}
.goods-info {
  flex: 1;
}
.goods-title {
  font-size: 30rpx;
  color: #222;
  margin-bottom: 10rpx;
  width: 70vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
}
.goods-price {
  font-size: 28rpx;
  color: #f56c6c;
  display: flex;
  justify-content: space-between;
  padding-right: 10px;
}
.goods-bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.picker {
  /* flex: 1; */
  margin-right: 16rpx;
}
.picker-inner {
  display: flex;
  align-items: center;
  border: 1px solid #eee;
  border-radius: 8rpx;
  padding: 16rpx;
  font-size: 28rpx;
  color: #666;
  background: #fafbfc;
}
.search {
  text-align: center;
  border: #eee 1px solid;
  padding: 5px;
  border-radius: 5px;
  height: 70rpx;
  width: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.picker-icon {
  width: 40rpx;
  height: 40rpx;
}
.numberinput {
  flex: 1;
  border: 1px solid #eee;
  border-radius: 8rpx;
  font-size: 28rpx;
  height: 70rpx;
  margin-right: 16rpx;
}
.submit-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  /* width: 100vw; */
  background: #007aff;
  color: #fff;
  border: none;
  border-radius: 0;
  /* padding: 26rpx 0; */
  font-size: 32rpx;
  z-index: 99;
  margin: 30rpx;
  border-radius: 16rpx;
}
</style>
